package com.beiing.tianshuai.tianshuai.freshnews;

import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.DiscoveryComment_RVAdapter;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.common.ui.ReportActivity;
import com.beiing.tianshuai.tianshuai.entity.DiscoveryCommentListBean;
import com.beiing.tianshuai.tianshuai.entity.DiscoveryDetailsBean;
import com.beiing.tianshuai.tianshuai.entity.DiscoveryIsPraiseBean;
import com.beiing.tianshuai.tianshuai.entity.DiscoveryPraiseBean;
import com.beiing.tianshuai.tianshuai.entity.FollowBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.fragment.EmotionCompleteFragment;
import com.beiing.tianshuai.tianshuai.freshnews.presenter.DiscoveryDetailPresenter;
import com.beiing.tianshuai.tianshuai.freshnews.view.DiscoveryDetailViewImpl;
import com.beiing.tianshuai.tianshuai.mine.ui.LoginActivity;
import com.beiing.tianshuai.tianshuai.mine.ui.NewPersonalIndexActivity;
import com.beiing.tianshuai.tianshuai.util.DateUtil;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.util.GlobalOnItemClickManagerUtils;
import com.beiing.tianshuai.tianshuai.util.NetBitmapUtils;
import com.beiing.tianshuai.tianshuai.widget.CircleImageView;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.ShowImageWebView;
import com.bumptech.glide.Glide;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.open.utils.ThreadManager;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.tianshuai.easypopup.EasyPopup;
import com.tianshuai.easypopup.HorizontalGravity;
import com.tianshuai.easypopup.VerticalGravity;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by LZQ on 2017/7/28.
 */

public class DiscoveryDetailActivity extends BaseActivity implements DiscoveryDetailViewImpl, View.OnClickListener {

    private DiscoveryDetailPresenter                        mPresenter;
    private DiscoveryComment_RVAdapter                      mAdapter;
    private List<DiscoveryCommentListBean.DataBean>         dataBeanList;
    private DiscoveryDetailsBean                            discoveryDetails;
    private String                                          uid;
    private String                                          publisher_uid;
    private String                                          fid;
    private InputMethodManager                              imm;
    private Dialog                                          bottomDialog;
    private Bitmap                                          thumb;
    private String                                          url;
    private Drawable                                        isFollowed, toFollowed;
    private Drawable                                        isPraised, unPraised;
    private MyIUiListener                                   mIUiListener;
    private Tencent                                         mTencent;
    private AlphaAnimation                                  mHideAnimation;
    private int                                             discoveryPosition;
    private int                                             praiseNum;

    private int sendType;
    private String cid;
    private String t_uid;
    private String t_name;
    private String comment;
    private int replyType;
    private String replyRid;

    private boolean emotionLayoutIsShow;
    private EasyPopup toolbarMorePopup;
    private EasyPopup orderByPopup;
    private int page = 0;                        // 评论页码
    private int pageSize = 10;                   // 评论每页数量
    private int orderByType = 0;                 // 评论排序类型 0--时间倒序 1--时间正序 2--热门倒序

    @BindView(R.id.title_iv_back)
    ImageView titleIvBack;                                  //toolBar返回键
    @BindView(R.id.title_head)
    CircleImageView titleHead;                              //toolBar圆形头像
    @BindView(R.id.discovery_detail_name)
    TextView discoveryDetailName;                           //toolBar用户名
    @BindView(R.id.discovery_detail_share)
    ImageButton discoveryDetailShare;                       // 分享
    @BindView(R.id.discovery_detail_more)
    ImageButton discoveryDetailMore;                        // 更多
    @BindView(R.id.discovery_detail_time)
    TextView discoveryDetailTime;                           //时间
    @BindView(R.id.discovery_detail_watch)
    TextView discoveryDetailWatch;                          //查看次数
    @BindView(R.id.discovery_detail_like)
    TextView discoveryDetailLike;                           //收藏次数
    @BindView(R.id.discovery_detail_title)
    TextView discoveryDetailTitle;                          //发现标题
    @BindView(R.id.discovery_detail_web)
    ShowImageWebView discoveryDetailWeb;
    @BindView(R.id.discovery_detail_praise)
    LinearLayout mPraise;                                   //点赞
    @BindView(R.id.iv_praise)
    ImageView ivPraise;
    @BindView(R.id.tv_praise)
    TextView tvPraise;
    @BindView(R.id.discovery_detail_comment)
    LinearLayout mComment;                                  //评论
    @BindView(R.id.discovery_detail_recycler)
    RecyclerView mRecyclerView;                             //评论列表
    @BindView(R.id.discovery_detail_ll_comment)
    LinearLayout mLlComment;                                //评论输入框
    @BindView(R.id.discovery_detail_edit)
    EditText mCommentEdit;                                  //评论编辑框
    @BindView(R.id.discovery_detail_send)
    TextView mCommentSend;                                  //发送评论
    @BindView(R.id.nstScrollView)
    ScrollView mScrollView;                                 //ScrollView
    @BindView(R.id.loading_background)
    View mLoadingBackground;                                //加载动画
    @BindView(R.id.discovery_comment_tittle)
    TextView commentTittle;                                 //最新评论
    @BindView(R.id.iv_face)
    ImageView ivFace;
    @BindView(R.id.iv_keyboard)
    ImageView ivKeyBoard;
    @BindView(R.id.fl_emotionview_main)
    FrameLayout mEmotionLayout;
    @BindView(R.id.btn_order_by)
    ImageButton btnOrderBy;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_discovery_detail;
    }

    @Override
    protected void init() {
        CustomProgressDialog.showLoading(mContext, "", true);
        CustomProgressDialog.setCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        initData();
        initRecyclerView();
        initPresenter();
        initPopupWindow();
        setListener();
        initEmotionMainFragment();
    }

    private void initEmotionMainFragment() {
        GlobalOnItemClickManagerUtils globalOnItemClickManagerUtils = GlobalOnItemClickManagerUtils.getInstance(mContext);
        globalOnItemClickManagerUtils.attachToEditText(mCommentEdit);
        EmotionCompleteFragment emotionCompleteFragment = new EmotionCompleteFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.fl_emotionview_main, emotionCompleteFragment);
        transaction.commit();
    }

    private void initPresenter() {
        mPresenter = new DiscoveryDetailPresenter(this);
        mPresenter.getDiscoveryDetail(fid);
        mPresenter.getDiscoveryCommentList(fid, page, pageSize, orderByType);
        mPresenter.getDiscoveryIsPraise(uid, fid);
    }

    private void initPopupWindow(){
        toolbarMorePopup = new EasyPopup(mContext)
                .setContentView(R.layout.menu_discovery_toolbar_more)
                .setAnimationStyle(R.style.QQPopAnim)
                .setFocusAndOutsideEnable(true)
                .createPopup();

        orderByPopup = new EasyPopup(mContext)
                .setContentView(R.layout.menu_dynamic_comment_order_by)
                .setAnimationStyle(R.style.QQPopAnim)
                .setFocusAndOutsideEnable(true)
                .createPopup();
    }

    private void initData() {
        Intent intent = this.getIntent();
        discoveryPosition = intent.getIntExtra("position", -1);
        uid = UserInfoBean.getUid(mContext);
        fid = intent.getStringExtra("fresh_id");
        imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        url = "http://www.tianshuai.com.cn/index.php/Home/Active/news_detail/id/" + fid;

        isFollowed = getResources().getDrawable(R.drawable.icon_add_32);
        mTencent = Tencent.createInstance("1106377834", getApplicationContext());       //新建Tencent实例
        mIUiListener = new MyIUiListener();
        isPraised = getResources().getDrawable(R.drawable.ic_dynamic_praise_red);
        unPraised = getResources().getDrawable(R.drawable.ic_dynamic_praise);
    }

    private void initRecyclerView() {
        dataBeanList = new ArrayList<>();
        LinearLayoutManager manager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setNestedScrollingEnabled(false);
        mAdapter = new DiscoveryComment_RVAdapter(mContext, dataBeanList);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemViewClickListener(new DiscoveryComment_RVAdapter.OnItemViewClickListener() {
            @Override
            public void onItemClick(View view, int position, DiscoveryCommentListBean.DataBean dataBean) {
                mLlComment.setVisibility(View.VISIBLE);
                mCommentEdit.setFocusable(true);
                mCommentEdit.setFocusableInTouchMode(true);
                mCommentEdit.requestFocus();
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                sendType = 1;
                switch (dataBean.getTable_type()){
                    case "0":
                        mCommentEdit.setHint("回复" + dataBean.getName());
                        cid = dataBean.getId();
                        t_uid = dataBean.getUId();
                        t_name = dataBean.getName();
                        comment = dataBean.getReview();
                        replyType = 0;
                        break;
                    case "1":
                        mCommentEdit.setHint("回复" + dataBean.getF_name());
                        cid = dataBean.getCid();
                        t_uid = dataBean.getForm_uid();
                        t_name = dataBean.getF_name();
                        comment = dataBean.getContent();
                        replyType = 1;
                        replyRid = dataBean.getId();
                        break;
                }
            }

            @Override
            public void onItemViewClick(View view, int position) {
                switch (view.getId()){
                    case R.id.huodong_comment_head :
                        Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                        switch (dataBeanList.get(position).getTable_type()){
                            case "0":
                                intent.putExtra("uid", dataBeanList.get(position).getUId());
                                break;
                            case "1":
                                intent.putExtra("uid", dataBeanList.get(position).getForm_uid());
                                break;
                        }
                        startActivity(intent);
                        break;
                    case R.id.huodong_comment_praise :
                        switch (dataBeanList.get(position).getTable_type()){
                            case "0":
                                mPresenter.praiseComment(fid, uid, dataBeanList.get(position).getId());
                                break;
                            case "1":
                                mPresenter.praiseReply(fid, dataBeanList.get(position).getCid(), dataBeanList.get(position).getId(), uid, dataBeanList.get(position).getForm_uid());
                                break;
                        }
                        break;
                }
            }
        });

        mAdapter.setOnTextClickListener(new DiscoveryComment_RVAdapter.OnTextClickListener() {
            @Override
            public void onTextClick(View view, int position, DiscoveryCommentListBean.DataBean dataBean) {
                Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                intent.putExtra("uid", dataBean.getTo_uid());
                startActivity(intent);
            }
        });

        mAdapter.setOnItemLongClickListener(new DiscoveryComment_RVAdapter.OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, int position, DiscoveryCommentListBean.DataBean dataBean) {
                showPopupMenu(view, position, dataBean);
            }
        });
    }

    private void showPopupMenu(View view, final int position, final DiscoveryCommentListBean.DataBean dataBean){
        PopupMenu mPopupMenu = new PopupMenu(mContext, view);
        mPopupMenu.setGravity(Gravity.RIGHT);
        mPopupMenu.getMenuInflater().inflate(R.menu.comment_click_menu, mPopupMenu.getMenu());
        switch (dataBean.getTable_type()){
            case "0":
                if (dataBean.getUId().equals(uid)){
                    mPopupMenu.getMenu().findItem(R.id.item_delete).setVisible(true);
                } else {
                    mPopupMenu.getMenu().findItem(R.id.item_delete).setVisible(false);
                }
                break;
            case "1":
                if (dataBean.getForm_uid().equals(uid)){
                    mPopupMenu.getMenu().findItem(R.id.item_delete).setVisible(true);
                } else {
                    mPopupMenu.getMenu().findItem(R.id.item_delete).setVisible(false);
                }
                break;
        }

        mPopupMenu.show();
        mPopupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()){
                    case R.id.item_copy:
                        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        try {
                            cm.setText(URLDecoder.decode(dataBean.getTable_type().equals("0") ? dataBean.getReview() : dataBean.getContent(), "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        showShortText("已复制");
                        break;
                    case R.id.item_delete:
                        switch (dataBean.getTable_type()){
                            case "0":
                                mPresenter.deleteComment(dataBean.getId());
                                break;
                            case "1":
                                mPresenter.deleteReply(dataBean.getFid(), dataBean.getId(), uid);
                        }
                        mAdapter.deleteItem(position);
                        break;
                }
                return false;
            }
        });
    }

    @Override
    public void showDiscoveryDetail(DiscoveryDetailsBean discoveryDetailsBean) {
        discoveryDetails = discoveryDetailsBean;
        Glide.with(getApplicationContext())
                .load(discoveryDetailsBean.getData().getPhoto().equals("") ? R.mipmap.default_avatar :
                        HttpRequestConstant.USER_PIC_HEAD + discoveryDetailsBean.getData().getPhoto())
                .into(titleHead);
        discoveryDetailName.setText(discoveryDetailsBean.getData().getName());
        discoveryDetailTitle.setText(discoveryDetailsBean.getData().getTitle());
        discoveryDetailTime.setText(DateUtil.timeStamp2Date(discoveryDetailsBean.getData().getCreate_time(), "MM-dd"));
        discoveryDetailWatch.setText(discoveryDetailsBean.getData().getView());
        discoveryDetailLike.setText(discoveryDetailsBean.getData().getPraise());
        praiseNum = Integer.parseInt(discoveryDetailsBean.getData().getPraise());
        publisher_uid = discoveryDetailsBean.getData().getUId();

        String text = discoveryDetailsBean.getData().getArticle();
        String text1 = text.replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&quot;","").replaceAll("&amp;","&");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            discoveryDetailWeb.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        discoveryDetailWeb.getSettings().setJavaScriptEnabled(true);
        discoveryDetailWeb.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        discoveryDetailWeb.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    CustomProgressDialog.stopLoading();
                }
                super.onProgressChanged(view, newProgress);
            }
        });
        discoveryDetailWeb.setWebViewClient(new WebViewClient(){

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                discoveryDetailWeb.setImageClickListener();
                discoveryDetailWeb.parseHTML(view);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                showShortText("请检查您的网络设置");
            }
        });
        discoveryDetailWeb.loadDataWithBaseURL(null, text1, "text/html", "utf-8", null);
    }

    @Override
    public void showDiscoveryCommentList(DiscoveryCommentListBean commentListBean) {
        commentTittle.setText(MessageFormat.format("评论{0}", commentListBean.getData().size()));
        dataBeanList.clear();
        dataBeanList.addAll(commentListBean.getData());
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void showIsPraiseOrNot(DiscoveryIsPraiseBean isPraiseBean) {
        if (isPraiseBean.getCode() == 1){           //code为1已赞，0为没赞
            ivPraise.setImageResource(R.drawable.like_red_solid);
            tvPraise.setText("取消");
            discoveryDetailLike.setCompoundDrawablesWithIntrinsicBounds(isPraised, null, null, null);
        } else {
            ivPraise.setImageResource(R.drawable.like_gray_hollow);
            tvPraise.setText("喜欢");
            discoveryDetailLike.setCompoundDrawablesWithIntrinsicBounds(unPraised, null, null, null);
        }
    }

    @Override
    public void showPraisedResult(DiscoveryPraiseBean bean) {
        if (bean.getCode() == 200){
            ivPraise.setImageResource(R.drawable.like_red_solid);
            tvPraise.setText("取消");
            discoveryDetailLike.setCompoundDrawablesWithIntrinsicBounds(isPraised, null, null, null);
            discoveryDetailLike.setText(praiseNum + 1 + "");
            praiseNum += 1;
        } else {
            ivPraise.setImageResource(R.drawable.like_gray_hollow);
            tvPraise.setText("喜欢");
            discoveryDetailLike.setCompoundDrawablesWithIntrinsicBounds(unPraised, null, null, null);
            discoveryDetailLike.setText(praiseNum - 1 + "");
            praiseNum -= 1;
        }
    }

    @Override
    public void refreshComment() {
        mAdapter.notifyDataSetChanged();
    }

    private void setListener(){

        CustomProgressDialog.setListener(new CustomProgressDialog.OnDismiss() {
            @Override
            public void onDismissListener() {
                setHideAnimation(mLoadingBackground, 888);
            }
        });

        titleIvBack.setOnClickListener(this);
        mPraise.setOnClickListener(this);
        mComment.setOnClickListener(this);
        titleHead.setOnClickListener(this);
        mCommentSend.setOnClickListener(this);
        discoveryDetailShare.setOnClickListener(this);
        discoveryDetailLike.setOnClickListener(this);

        mScrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                imm.hideSoftInputFromWindow(mCommentEdit.getWindowToken(), 0);
                mLlComment.setVisibility(View.GONE);
                return false;
            }
        });

        //输入框输入监听
        mCommentEdit.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0 && !"".equals(s.toString().trim())){     //有文字内容
                    mCommentSend.setBackgroundResource(R.drawable.publish_blue);
                    mCommentSend.setClickable(true);
                } else {
                    mCommentSend.setBackgroundResource(R.drawable.publish_gray);       //没有文字内容
                    mCommentSend.setClickable(false);
                }
            }
        });

        mCommentEdit.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mEmotionLayout.setVisibility(View.GONE);
                ivKeyBoard.setVisibility(View.GONE);
                ivFace.setVisibility(View.VISIBLE);
                emotionLayoutIsShow = false;
                return false;
            }
        });

        ivFace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivFace.setVisibility(View.GONE);
                ivKeyBoard.setVisibility(View.VISIBLE);
                emotionLayoutIsShow = true;
                imm.hideSoftInputFromWindow(mCommentEdit.getWindowToken(), 0);
                mEmotionLayout.setVisibility(View.VISIBLE);
            }
        });

        ivKeyBoard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEmotionLayout.setVisibility(View.GONE);
                ivKeyBoard.setVisibility(View.GONE);
                ivFace.setVisibility(View.VISIBLE);
                emotionLayoutIsShow = false;
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                mCommentEdit.setFocusable(true);
                mCommentEdit.setFocusableInTouchMode(true);
                mCommentEdit.requestFocus();
            }
        });

        discoveryDetailMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPresenter.isFollowed(uid, publisher_uid);
                int i = view.getLayoutParams().width / 2 + DensityUtils.dp2px(mContext, 2);
                toolbarMorePopup.showAtAnchorView(view, VerticalGravity.BELOW, HorizontalGravity.ALIGN_RIGHT, i, -DensityUtils.dp2px(mContext, 15));
            }
        });

        btnOrderBy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initOrderByPopupWindow();
                int i = view.getLayoutParams().width / 2 + DensityUtils.dp2px(mContext, 6);
                orderByPopup.showAtAnchorView(view, VerticalGravity.BELOW, HorizontalGravity.ALIGN_RIGHT, i, -DensityUtils.dp2px(mContext, 5));
            }
        });
    }

    @Override
    public void showMorePopupWindow(FollowBean followBean){
        // 订阅
        LinearLayout llSubscribe = toolbarMorePopup.getView(R.id.action_subscribe_author);
        final TextView tvSubscribe = toolbarMorePopup.getView(R.id.tv_subscribe);
        // 收藏
        LinearLayout llCollect = toolbarMorePopup.getView(R.id.action_collect);
        TextView tvCollect = toolbarMorePopup.getView(R.id.tv_collect);
        // 举报
        LinearLayout llReport = toolbarMorePopup.getView(R.id.action_report);
        TextView tvReport = toolbarMorePopup.getView(R.id.tv_report);

        llCollect.setVisibility(View.GONE);
        if (followBean.getCode() == 1){
            tvSubscribe.setText("取消关注");
        } else {
            tvSubscribe.setText("关注作者");
        }

        llSubscribe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(uid)){
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    mPresenter.setFollowed(uid, publisher_uid);
                    if (tvSubscribe.getText().equals("取消关注")){
                        tvSubscribe.setText("关注作者");
                        showShortText("已取消关注");
                    } else {
                        tvSubscribe.setText("取消关注");
                        showShortText("关注成功");
                    }
                }
                toolbarMorePopup.dismiss();
            }
        });

        llCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        llReport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, ReportActivity.class);
                intent.putExtra("currency_id", fid);
                intent.putExtra("tid", "0");
                startActivity(intent);
                toolbarMorePopup.dismiss();
            }
        });
    }

    private void initOrderByPopupWindow(){
        // 最热
        TextView tvOrderByHot = orderByPopup.getView(R.id.action_order_by_hot);
        // 最新
        TextView tvOrderByNew = orderByPopup.getView(R.id.action_order_by_new);
        // 最先
        TextView tvOrderByOld = orderByPopup.getView(R.id.action_order_by_old);

        // 设置按热度排序点击事件
        tvOrderByHot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                orderByType = 2;
                mPresenter.getDiscoveryCommentList(fid, page, pageSize, orderByType);
                orderByPopup.dismiss();
            }
        });

        tvOrderByNew.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                orderByType = 0;
                mPresenter.getDiscoveryCommentList(fid, page, pageSize, orderByType);
                orderByPopup.dismiss();
            }
        });

        // 设置按时间排序点击事件
        tvOrderByOld.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                orderByType = 1;
                mPresenter.getDiscoveryCommentList(fid, page, pageSize, orderByType);
                orderByPopup.dismiss();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.title_iv_back:
                finish();
                break;
            case R.id.title_head:
                Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                intent.putExtra("uid", discoveryDetails.getData().getUId());
                startActivity(intent);
                break;
            case R.id.discovery_detail_share:
                showShareDialog();
                break;
//            case R.id.discovery_detail_attention:
//                break;
            case R.id.discovery_detail_praise:
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))){
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    mPresenter.praiseDiscovery(uid, fid, discoveryPosition);
                }
                break;
            case R.id.discovery_detail_comment:
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))){
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    if (mLlComment.getVisibility() == View.GONE){
                        mLlComment.setVisibility(View.VISIBLE);
                        mCommentEdit.setFocusable(true);
                        mCommentEdit.setFocusableInTouchMode(true);
                        mCommentEdit.requestFocus();
                        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                        mEmotionLayout.setVisibility(View.GONE);
                        emotionLayoutIsShow = false;
                    }
                }
                sendType = 0;
                break;
            case R.id.discovery_detail_send:            //发表评论
                if (!TextUtils.isEmpty(mCommentEdit.getText().toString().trim())){
                    String contentUTF8 = null;
                    try {
                        contentUTF8 = URLEncoder.encode(mCommentEdit.getText().toString().trim(), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        contentUTF8 = mCommentEdit.getText().toString().trim();
                        e.printStackTrace();
                    }
                    switch (sendType){
                        case 0:
                            mPresenter.commentDiscovery(uid, fid, contentUTF8);
                            break;
                        case 1:
                            mPresenter.addReply(fid, cid, uid, t_uid, contentUTF8, comment, replyType, replyRid);
                            break;
                    }
                    mLlComment.setVisibility(View.GONE);
                    mCommentEdit.setText("");
                    imm.hideSoftInputFromWindow(mCommentEdit.getWindowToken(), 0);
                    mEmotionLayout.setVisibility(View.GONE);
                }
                break;
            case R.id.discovery_detail_like:
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))){
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    mPresenter.praiseDiscovery(uid, fid, discoveryPosition);
                }
                break;
        }
    }

    private void showShareDialog() {
        bottomDialog = new Dialog(mContext, R.style.BottomDialog);
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.dialog_interest_detail_bottom_share, null);

        RadioButton wechat_friends = contentView.findViewById(R.id.rb_wechat_friends);
        RadioButton wechat_circle = contentView.findViewById(R.id.rb_wechat_circle);
        RadioButton qq_friends = contentView.findViewById(R.id.rb_qq_friends);
        RadioButton qzone = contentView.findViewById(R.id.rb_qzone);

        wechat_friends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {        //分享给微信好友
                shareToWeChatWithWebpage(mContext, url, discoveryDetails.getData().getTitle(), discoveryDetails.getData().getTitle(), 0);
                bottomDialog.dismiss();
            }
        });
        wechat_circle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {        //分享到朋友圈
                shareToWeChatWithWebpage(mContext, url, discoveryDetails.getData().getTitle(), discoveryDetails.getData().getTitle(), 1);
                bottomDialog.dismiss();
            }
        });
        qq_friends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareToQQ(discoveryDetails.getData().getTitle(), discoveryDetails.getData().getTitle(), url);
                bottomDialog.dismiss();
            }
        });
        qzone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareToQZone(discoveryDetails.getData().getTitle(), discoveryDetails.getData().getTitle(), url);
                bottomDialog.dismiss();
            }
        });

        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);

        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);

        bottomDialog.show();
        bottomDialog.setCanceledOnTouchOutside(true);
    }

    /**
     * 分享到微信
     *
     * @param context       上下文
     * @param url            分享网页的url
     * @param title         分享出去的标题
     * @param description   分享出去的摘要
     * @param scene          0 / 1   好友/朋友圈
     */
    private void shareToWeChatWithWebpage(Context context, String url, String title, String description, final int scene) {
        final IWXAPI iwxapi = WXAPIFactory.createWXAPI(context, AppConstant.WX_APP_ID);

        if (!iwxapi.isWXAppInstalled()){
            showShortText("您尚未安装微信");
            return;
        }

        WXWebpageObject wxWebpageObject = new WXWebpageObject();
        wxWebpageObject.webpageUrl = url;
        final WXMediaMessage wxMediaMessage = new WXMediaMessage(wxWebpageObject);
        wxMediaMessage.mediaObject = wxWebpageObject;
        wxMediaMessage.title = title;
        wxMediaMessage.description = description;
//        wxMediaMessage.thumbData =
//                ImageManager.bmpToByteArray(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_share_invite), true);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String cover = discoveryDetails.getData().getCover();
                if (cover.contains(",")) {
                    String[] split = cover.split(",");
                    cover = split[0];
                }
                thumb = NetBitmapUtils.getBitmap(HttpRequestConstant.FRESH_COVER_URL + cover);
                thumb = Bitmap.createScaledBitmap(thumb, 200, 200, true);
                wxMediaMessage.setThumbImage(thumb);
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = wxMediaMessage;
                req.scene = scene;
                iwxapi.sendReq(req);
            }
        }).start();
    }

    private Bundle params;
    private void shareToQQ(String title, String summary, String url){
        params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, title);         //标题
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary);     //摘要
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url);      //内容地址

        ThreadManager.getMainHandler().post(new Runnable() {
            @Override
            public void run() {
                mTencent.shareToQQ(DiscoveryDetailActivity.this, params, mIUiListener);
            }
        });
    }

    private Bundle params1;
    private void shareToQZone(String title, String summary, String url){
        params1 = new Bundle();
        params1.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params1.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);         //标题
        params1.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, summary);     //摘要
        params1.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, url);      //内容地址
        params1.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, new ArrayList<String>());

        ThreadManager.getMainHandler().post(new Runnable() {
            @Override
            public void run() {
                mTencent.shareToQzone(DiscoveryDetailActivity.this, params1, mIUiListener);
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Tencent.onActivityResultData(requestCode, resultCode, data, mIUiListener);
        if (requestCode == Constants.REQUEST_API){
            if (resultCode == Constants.REQUEST_QQ_SHARE || resultCode == Constants.REQUEST_QZONE_SHARE || resultCode == Constants.REQUEST_OLD_SHARE){
                Tencent.handleResultData(data, mIUiListener);
            }
        }
    }
    class MyIUiListener implements IUiListener {
        @Override
        public void onComplete(Object o) {
            showShortText("分享成功");
        }

        @Override
        public void onError(UiError uiError) {
            showShortText("分享失败");
        }

        @Override
        public void onCancel() {
            showShortText("分享取消");
        }
    }
    @Override
    public void showError(int errorType) {
        switch (errorType){
            case 0:     //没有评论
                commentTittle.setText("还没有评论，来抢个沙发吧！");
        }
    }

    @Override
    public void showProgress() {
//        CustomProgressDialog.showLoading(mContext, "请稍后，正在努力加载...", true);
    }

    @Override
    public void hideProgress() {
//        CustomProgressDialog.stopLoading();
    }

    @Override
    public void showFollowed(FollowBean followBean) {
        if (followBean.getCode() == 0){

        }
    }

    public void setHideAnimation(final View view, int duration) {
        if (null == view || duration < 0) {
            return;
        }

        if (null != mHideAnimation) {
            mHideAnimation.cancel();
        }
        // 监听动画结束的操作
        mHideAnimation = new AlphaAnimation(1.0f, 0.0f);
        mHideAnimation.setDuration(duration);
        mHideAnimation.setFillAfter(true);
        mHideAnimation.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation arg0) {

            }

            @Override
            public void onAnimationRepeat(Animation arg0) {

            }

            @Override
            public void onAnimationEnd(Animation arg0) {
                view.setVisibility(View.GONE);
            }
        });
        view.startAnimation(mHideAnimation);
    }

    @Override
    protected void onResume() {
        uid = UserInfoBean.getUid(mContext);
        super.onResume();
    }

    @Override
    public void onBackPressed() {
        if (emotionLayoutIsShow){
            mEmotionLayout.setVisibility(View.GONE);
            emotionLayoutIsShow = false;
        } else {
            super.onBackPressed();
        }
    }
}
